<script>
	import Vue from 'vue'
	export default {
		data() {
			return {
				pingTimer: 0
			}
		},
		onLaunch: function() {
			uni.getSystemInfo({
				success: function(e) {
					// #ifndef MP
					Vue.prototype.StatusBar = e.statusBarHeight;
					if (e.platform == 'android') {
						Vue.prototype.CustomBar = e.statusBarHeight + 50;
					} else {
						Vue.prototype.CustomBar = e.statusBarHeight + 45;
					};
					// #endif

					// #ifdef MP-WEIXIN
					Vue.prototype.StatusBar = e.statusBarHeight;
					let custom = wx.getMenuButtonBoundingClientRect();
					Vue.prototype.Custom = custom;
					Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
					// #endif		

					// #ifdef MP-ALIPAY
					Vue.prototype.StatusBar = e.statusBarHeight;
					Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
					// #endif
				}
			})
		},
		onShow: function() {
			this.ws()
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			// 发送信息
			wsSend(data){
				uni.sendSocketMessage({
					data: JSON.stringify(data)
				});
			},
			ws(){
				console.log(111)
				if(this.globalData.user_token){
					this.globalData.user_token
					// 页面加载后自动连接websocket
					uni.connectSocket({
						url: 'wss://wxzx.gzzww.cn/ws',
						protocols: this.globalData.user_token,
						
					});
					
					// 监听连接成功
					uni.onSocketOpen((res)=>{
						console.log('WebSocket连接已打开！');
						this.ping()
						// 通过 WebSocket 连接发送数据
						uni.sendSocketMessage({
							data: JSON.stringify({
								action:'companyInfo'
							})
						});
					});
					
					// 监听连接失败
					uni.onSocketError((res)=> {
					  console.log('WebSocket连接打开失败，请检查！');
					});	
					
					// 监听连接关闭
					uni.onSocketClose((res)=>{
						//断开后停止ping心跳检测
						 setTimeout(()=>{
							 this.ws()
						 },5000)
					});
					
					
					// 监听获取数据
					uni.onSocketMessage((res)=>{
						if(res.data == '"PONG"') return;
						var data = JSON.parse(res.data);
						// 获取总页面
						var pages = getCurrentPages();
						// 获取当前页面
						var page = pages[pages.length - 1];
						
						// 触发当前页面的onWsMessage方法。。。。。
						if(page.$vm.onWsMessage){
							page.$vm.onWsMessage(data)
						}
					});
				}
			},
			ping(){
				this.pingTimer = setTimeout(()=>{
					uni.sendSocketMessage({
						data: 'PING'
					});
					this.ping()
				}, 5000);
			},
		}
	}
</script>

<style>
	@import "colorui/main.css";
	@import "colorui/icon.css";
	@import "static/icon.css";
	/*每个页面公共css */
	
	.bg-maincolor{
		background-color: rgb(59,115,246);
		color: #fff;
		font-size: 35rpx;
		font-weight: 600rpx;
	}
	.cu-modal textarea{
		display: none;
	}
	.cu-modal.show textarea{
		display: block;
	}
	
	
</style>
